package bx.com.smartcashier.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.smartdevice.aidl.ICallBack;

import java.util.List;

import bx.com.smartcashier.R;
import bx.com.smartcashier.common.MessageType;
import bx.com.smartcashier.config.ClientConfig;
import bx.com.smartcashier.mode.SmartShopOrderDetailVO;
import bx.com.smartcashier.mode.SmartShopOrderVO;
import bx.com.smartcashier.utils.BaseActivity;
import bx.com.smartcashier.zxing.Constants;
import bx.com.smartcashier.zxing.activity.CaptureActivity;

public class CashRegisterSucessedActivity extends BaseActivity {

    //线程运行标志 the running flag of thread
    private boolean runFlag = true;
    //打印机检测标志 the detect flag of printer
    private boolean detectFlag = false;
    //打印机连接超时时间 link timeout of printer
    private float PINTER_LINK_TIMEOUT_MAX = 30 * 1000L;
    //标签打印标记 the flag of tag print
    private boolean autoOutputPaper = false;

    private boolean hasSurface;

    private String firstCodeStr = "";
    private String text;
    MediaPlayer player;
    Vibrator vibrator;

    private Button btnPrintTest;//打印
    private Button btnCamereSacn;//摄像头扫描

    private DetectPrinterThread mDetectPrinterThread;


    ICallBack.Stub mCallback = new ICallBack.Stub() {

        @Override
        public void onReturnValue(byte[] buffer, int size)
                throws RemoteException {
            String codeStr = new String(buffer, 0, size);
            if(ClientConfig.getBoolean(ClientConfig.SCAN_REPEAT)){
                if(firstCodeStr.equals(codeStr)){
                    vibrator.vibrate(100);
                }
            }
            if(ClientConfig.getBoolean(ClientConfig.APPEND_RINGTONE)){
                player.start();
            }
            if(ClientConfig.getBoolean(ClientConfig.APPEND_VIBRATE)){
                vibrator.vibrate(100);
            }
            firstCodeStr = codeStr;
            text += codeStr+"\n";
            sendMessage(MessageType.BaiscMessage.SCAN_RESULT_GET_SUCCESS, text);
        }
    };


    TextView tvReturn_Home;
    Button btnReturnHome,btnReturnCashRegister;
    SmartShopOrderVO data;
    private boolean ifFirst=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cash_register_sucessed);

        initViews();
        setOnlistners();
        getData();
        mDetectPrinterThread = new DetectPrinterThread();
        mDetectPrinterThread.start();
        vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        player = MediaPlayer.create(getApplicationContext(), R.raw.scan);
    }


    class DetectPrinterThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (runFlag) {
                float start_time = SystemClock.currentThreadTimeMillis();
                float end_time = 0;
                float time_lapse = 0;
                if (detectFlag) {
                    //检测打印是否正常 detect if printer is normal
                    try {
                        if (mIzkcService != null) {
                            String printerSoftVersion = mIzkcService.getFirmwareVersion1();
                            if (TextUtils.isEmpty(printerSoftVersion)) {
                                mIzkcService.setModuleFlag(module_flag);
                                end_time = SystemClock.currentThreadTimeMillis();
                                time_lapse = end_time - start_time;
//								enableOrDisEnableKey(false);
                                if (time_lapse > PINTER_LINK_TIMEOUT_MAX) {
                                    detectFlag = false;
                                    //打印机连接超时 printer link timeout
                                    sendEmptyMessage(MessageType.BaiscMessage.PRINTER_LINK_TIMEOUT);
                                }
                            } else {
                                //打印机连接成功 printer link success
                                sendMessage(MessageType.BaiscMessage.DETECT_PRINTER_SUCCESS, printerSoftVersion);
                                detectFlag = false;
                            }
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                }
                SystemClock.sleep(200);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constants.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constants.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constants.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            Toast.makeText(this,"扫描成功:"+scanResult,Toast.LENGTH_SHORT).show();

        }
    }

    /**
     * 开始扫描
     */
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // android 6.0以上需要动态申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constants.REQ_PERM_CAMERA);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(this, CaptureActivity.class);
        startActivityForResult(intent, Constants.REQ_QR_CODE);
    }
    @Override
    protected void onResume() {
        //开始检测打印机 begin to detect printer
        detectFlag = true;
        //设置打印可以 点击

        super.onResume();
    }
    @Override
    protected void handleStateMessage(Message message) {
        super.handleStateMessage(message);
        switch (message.what) {
            //服务绑定成功 service bind success
            case MessageType.BaiscMessage.SEVICE_BIND_SUCCESS:
//				Toast.makeText(this, getString(R.string.service_bind_success), Toast.LENGTH_SHORT).show();
                registerCallbackAndInitScan();
                break;
            //服务绑定失败 service bind fail
            case MessageType.BaiscMessage.SEVICE_BIND_FAIL:
//				Toast.makeText(this, getString(R.string.service_bind_fail), Toast.LENGTH_SHORT).show();
                break;
            //打印机连接成功 printer link success
            case MessageType.BaiscMessage.DETECT_PRINTER_SUCCESS:
                String msg = (String) message.obj;
                checkPrintStateAndDisplayPrinterInfo(msg);
                if(ifFirst){
                    print();
                    ifFirst=false;
                }
                break;
            //打印机连接超时 printer link timeout
            case MessageType.BaiscMessage.PRINTER_LINK_TIMEOUT:
                Toast.makeText(this, getString(R.string.printer_link_timeout), Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private String line="--------------------------------";
    // 占位符
    private   int GOODS_NAME_LENGTH = 4;
    /**
     * 打印操作
     */
    private void print() {

        try {
            mIzkcService.setAlignment(1);
            mIzkcService.printGBKText(data.getCompanyName()+"    "+data.getShopName() + "\n");
            mIzkcService.setAlignment(0);
            mIzkcService.printGBKText("*******************************\n");
            mIzkcService.printGBKText("单号：\n");
            mIzkcService.printGBKText(line+"\n");
            mIzkcService.createQRCode(data.getBillSn()+"\n",2,10);
            mIzkcService.printGBKText(data.getBillSn()+"\n");
//            mIzkcService.printGBKText("特价商品不退不换\n\n");
            mIzkcService.printGBKText("销售时间:"+data.getGmtCreate()+"\n");
            mIzkcService.printGBKText("收款方式:"+data.getPayTypeValue()+"\n");
            mIzkcService.printGBKText("数量:"+data.getCount()+"\n");
            mIzkcService.printGBKText("金额总计:"+data.getAmount()+"\n");
            mIzkcService.printGBKText("优惠金额:0.00元"+"\n");
            mIzkcService.printGBKText(line+"\n");
            mIzkcService.printGBKText("商品信息:"+"\n");
            mIzkcService.printGBKText("款号   数量   单价   折扣   成交价"+"\n");
            mIzkcService.printGBKText(line+"\n");
            mIzkcService.printGBKText("会员商品"+"\n");
            List<SmartShopOrderDetailVO> smartShopOrderDetailVOs = data.getSmartShopOrderDetailVOS();
            for (int i = 0; i <smartShopOrderDetailVOs.size() ; i++) {

                SmartShopOrderDetailVO one = smartShopOrderDetailVOs.get(i);

                mIzkcService.printGBKText(one.getGoodsCode()+"   "+one.getCount()+"   "+one.getRetailPrice()+"   "+one.getDiscountRate()+"   "+one.getDiscountPrice()+"\n\n");

            }

            mIzkcService.printGBKText("客户签名:\n\n");
            mIzkcService.printGBKText("\n\n");
            mIzkcService.printGBKText("\n\n");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册扫描监听
     */
    private void registerCallbackAndInitScan() {
        // 注册回调接口
        try {
            mIzkcService.registerCallBack("Scanner", mCallback);
            if(!mIzkcService.isScanning()) mIzkcService.openScan(ClientConfig.getBoolean(ClientConfig.OPEN_SCAN));
            mIzkcService.dataAppendEnter(ClientConfig.getBoolean(ClientConfig.DATA_APPEND_ENTER));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void checkPrintStateAndDisplayPrinterInfo(String msg) {
        // 设置打印可以进行
        String status;
        String aidlServiceVersion;
        try {
            status = mIzkcService.getPrinterStatus();

            aidlServiceVersion = mIzkcService.getServiceVersion();
            //打印自检信息
//			mIzkcService.printerSelfChecking();
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    @Override
    protected void onDestroy() {
        if (mDetectPrinterThread != null) {
            runFlag = false;
            mDetectPrinterThread.interrupt();
            mDetectPrinterThread = null;
        }
        //禁止打印
        if (mIzkcService != null) try {
            mIzkcService.sendRAWData("printer", new byte[]{0x1E, 0x03, 0x00,
                    (byte) 0xBF, (byte) 0xD8, (byte) 0xD6, (byte) 0xC6});
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }


    private void getData() {

        Bundle extr = getIntent().getExtras();
        if(extr!=null){
//            data= extr.getParcelable("data");
            data= (SmartShopOrderVO) extr.get("data");
        }

    }

    private void setOnlistners() {
        tvReturn_Home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setClass(CashRegisterSucessedActivity.this,HomeActivity.class);
                startActivity(intent);
                finish();
            }
        });

        btnReturnHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setClass(CashRegisterSucessedActivity.this,HomeActivity.class);
                startActivity(intent);
                finish();

            }
        });
        btnReturnCashRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setClass(CashRegisterSucessedActivity.this,CashRegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    private void initViews() {
        tvReturn_Home=findViewById(R.id.tv_return_home);
        btnReturnHome=findViewById(R.id.btn_return_home);
        btnReturnCashRegister=findViewById(R.id.btn_go_cashregister);
    }

}
